from rest_framework.mixins import CreateModelMixin, ListModelMixin, UpdateModelMixin, DestroyModelMixin, \
    RetrieveModelMixin
from rest_framework.response import Response


class DigCreateModelMixin(CreateModelMixin):
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        # 1.异常处理
        if not serializer.is_valid():
            return Response({'code': 1000, 'detail': serializer.errors})
        # 2。优化perform_create
        res = self.perform_create(serializer)
        # 3. 返回数据的处理
        return res or Response({"code": 10086, 'data': serializer.data})


class DigListModelMixin(ListModelMixin):
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return Response({"code": 0, 'data': serializer.data})

        serializer = self.get_serializer(queryset, many=True)
        return Response({"code": 0, 'data': serializer.data})


class DigDestroyModelMixin(DestroyModelMixin):
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        res = self.perform_destroy(instance)
        return res or Response({'code': 0})


class DigUpdateModelMixin(UpdateModelMixin):
    def destroy(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        if not serializer.is_valid():
            return Response({"code": 0, 'detail': serializer.errors})
        res = self.perform_update(serializer)
        return res or Response({"code": 0, 'data': serializer.data})
